package com.itx.gatewayx.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itx.gatewayx.common.R;
import com.itx.gatewayx.domain.User;
import com.itx.gatewayx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 用户控制器
 *
 * @author itx
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 检查用户名是否已存在
     */
    @GetMapping("/check-username")
    public R<Boolean> checkUsername(@RequestParam("username") String username) {
        boolean exists = userService.checkUsernameExists(username);
        return R.ok(exists);
    }

    /**
     * 检查邮箱是否已存在
     */
    @GetMapping("/check-email")
    public R<Boolean> checkEmail(@RequestParam("email") String email) {
        boolean exists = userService.checkEmailExists(email);
        return R.ok(exists);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody Map<String, String> loginParams) {
        // 添加调试信息
        System.out.println("进入登录接口");
        System.out.println("登录参数: " + loginParams);
        
        String username = loginParams.get("username");
        String password = loginParams.get("password");
        
        System.out.println("用户名: " + username);
        System.out.println("密码长度: " + (password != null ? password.length() : 0));
        
        try {
            Map<String, Object> result = userService.login(username, password);
            System.out.println("登录成功, 返回token");
            return R.ok(result);
        } catch (Exception e) {
            System.out.println("登录异常: " + e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody User user) {
        // 参数校验
        if (user == null) {
            return R.fail("用户信息不能为空");
        }
        
        // 打印请求参数，用于调试
        System.out.println("注册请求参数：" + user);
        System.out.println("用户名：" + user.getUsername());
        System.out.println("密码：" + user.getPassword());
        System.out.println("邮箱：" + user.getEmail());
        
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return R.fail("用户名不能为空");
        }
        
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return R.fail("密码不能为空");
        }
        
        if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
            return R.fail("邮箱不能为空");
        }
        
        boolean result = userService.register(user);
        return R.ok(result);
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public R<Map<String, Object>> refreshToken(@RequestBody Map<String, String> refreshParams) {
        String refreshToken = refreshParams.get("refreshToken");
        
        Map<String, Object> result = userService.refreshToken(refreshToken);
        return R.ok(result);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public R<User> getUserInfo(@RequestParam("userId") Long userId) {
        User user = userService.getUserInfo(userId);
        return R.ok(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public R<Boolean> updateUserInfo(@RequestBody User user) {
        boolean result = userService.updateUserInfo(user);
        return R.ok(result);
    }

    /**
     * 修改密码
     */
    @PostMapping("/password")
    public R<Boolean> changePassword(@RequestBody Map<String, String> passwordParams) {
        Long userId = Long.valueOf(passwordParams.get("userId"));
        String oldPassword = passwordParams.get("oldPassword");
        String newPassword = passwordParams.get("newPassword");
        
        boolean result = userService.changePassword(userId, oldPassword, newPassword);
        return R.ok(result);
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public R<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) {
        // 此处需要实现文件上传逻辑
        // 返回头像URL
        return R.ok("avatar_url");
    }
    
    /**
     * 获取用户列表（管理员权限）
     */
    @GetMapping("/list")
    public R<Page<User>> getUserList(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "role", required = false) String role) {
        
        Page<User> userPage = userService.getUserList(current, size, username, role);
        return R.ok(userPage);
    }
    
    /**
     * 更新用户状态（管理员权限）
     */
    @PutMapping("/status")
    public R<Boolean> updateUserStatus(@RequestBody Map<String, Object> statusParams) {
        Long userId = Long.valueOf(statusParams.get("userId").toString());
        Integer status = Integer.valueOf(statusParams.get("status").toString());
        
        boolean result = userService.updateUserStatus(userId, status);
        return R.ok(result);
    }
    
    /**
     * 设置用户为发布者（管理员权限）
     */
    @PutMapping("/publisher")
    public R<Boolean> setPublisher(@RequestBody Map<String, Object> publisherParams) {
        Long userId = Long.valueOf(publisherParams.get("userId").toString());
        Boolean isPublisher = Boolean.valueOf(publisherParams.get("isPublisher").toString());
        
        boolean result = userService.setPublisher(userId, isPublisher);
        return R.ok(result);
    }
} 